package com.bjsxt.homework5;

public class PrintABC {
    private int state; // 用来标记当前应该由哪个线程打印
    private final Object lock = new Object();

    public static void main(String[] args) {
        PrintABC printABC = new PrintABC();
        Thread threadA = new Thread(printABC.new Printer('a', 0));
        Thread threadB = new Thread(printABC.new Printer('b', 1));
        Thread threadC = new Thread(printABC.new Printer('c', 2));

        threadA.start();
        threadB.start();
        threadC.start();
    }

    class Printer implements Runnable {
        private final char letter;
        private final int targetState;

        Printer(char letter, int targetState) {
            this.letter = letter;
            this.targetState = targetState;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    while (state % 3 != targetState) {
                        try {
                            lock.wait(); // 如果不是自己的状态，就等待
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt(); // 保留中断状态
                            return;
                        }
                    }
                    System.out.print(letter); // 打印字母
                    state++; // 更新状态
                    lock.notifyAll(); // 唤醒所有等待中的线程
                }
            }
        }
    }
}